<template>
  <div>
    <!-- 头部 -->
    <hm-header>注册</hm-header>
    <!-- logo -->
    <hm-logo></hm-logo>

    <!-- 文本框部分 -->
    <hm-input
      v-model="username"
      ref="username"
      :rule="/^1\d{3,10}$/"
      message="用户名格式不合格"
      type="text"
      placeholder="用户名"
    ></hm-input>
    <hm-input
      v-model="nickname"
      ref="nickname"
      :rule="/^[\u4e00-\u9fa5]{3,7}$/"
      message="昵称格式不合格"
      type="text"
      placeholder="昵称"
    ></hm-input>
    <hm-input
      v-model="password"
      ref="password"
      :rule="/^\d{3,6}$/"
      message="密码格式不合格"
      type="password"
      placeholder="密码"
    ></hm-input>

    <!-- 注册按钮 -->
    <hm-button @click="register">注册</hm-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      nickname: "",
      password: ""
    };
  },
  methods: {
    register() {
      // 注冊請求之前 進行一次校驗攔截
      let isok1 = this.$refs.username.validate(this.username);
      let isok2 = this.$refs.nickname.validate(this.nickname);
      let isok3 = this.$refs.password.validate(this.password);

      if (!isok1 || !isok2 || !isok3) {
        this.$toast.fail("校验格式不合格");
        return;
      }
      // 注册请求
      this.$axios
        .post("/register", {
          username: this.username,
          nickname: this.nickname,
          password: this.password
        })
        .then(res => {
          console.log("注册结果", res);
          if (res.data.statusCode === 200) {
            this.$toast.success("注册成功");

            // 跳转到登录
            // 方式1 :
            // this.$router.push({
            //   path: "/login",
            //   query: {
            //     username: this.username,
            //     password: this.password
            //   }
            // });
            // 方式2
            this.$router.push({
              name: "login",
              params: {
                username: this.username,
                password: this.password
              }
            });
          } else {
            this.$toast.fail(res.data.message);
          }
        });
    }
  }
};
</script>

<style scoped>
h1 {
  color: red;
}
</style>
